import {AfterContentInit, Component, OnDestroy, OnInit, ViewEncapsulation} from '@angular/core';
import {HomeService} from "../home.service";
import {SettingUrl} from "../../../public/setting/setting_url";
import IEditorConstructionOptions = monaco.editor.IEditorConstructionOptions;

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit, AfterContentInit, OnDestroy {
  public editorOptions: IEditorConstructionOptions = {
    theme: 'vs-dark',
    value: '',
    readOnly: true,
    scrollBeyondLastLine: false,
    lineNumbers: 'off',
    minimap: {
      enabled: false
    },
    scrollbar: {
      verticalScrollbarSize: 5
    }
  };
  public timer: any;
  public logSocket1: WebSocket;
  public logSocket2: WebSocket;
  public logSocket3: WebSocket;
  public logSocket4: WebSocket;
  public logData1: string = '';
  public logData2: string = '';
  public logData3: string = '';
  public logData4: string = '';
  public logEditor1: any;
  public logEditor2: any;
  public logEditor3: any;
  public logEditor4: any;
  public states: any = {};//状态

  constructor(private homeService: HomeService) {
  }

  ngAfterContentInit(): void {
  }

  ngOnInit() {
    //延迟创建链接，确保editor渲染完成后创建socket链接
    setTimeout(_ => {
      this.getState();
    }, 1000);
    this.timer = setInterval(_ => {
      this.getState()
    }, 8000)
  }

  /**
   * 创建webSocket
   */
  createSocket1() {
    this.logSocket1 = new WebSocket(SettingUrl.URL.socket1);
    this.logSocket1.onmessage = (event) => {
      if (event.data) {
        let res = JSON.parse(event.data);
        this.logData1 += `结果:[${res.success}]，数据:${res.data || ' '}，信息:${res.info}\n`;
      }
      this.scrollBottom();
    };
    this.logSocket1.onerror = (err) => console.log(err);
  }

  /**
   * 创建webSocket
   */
  createSocket2() {
    this.logSocket2 = new WebSocket(SettingUrl.URL.socket2);
    this.logSocket2.onmessage = (event) => {
      if (event.data) {
        let res = JSON.parse(event.data);
        this.logData2 += `结果:[${res.success}]，数据:${res.data || ' '}，信息:${res.info}\n`;
      }
      this.scrollBottom();
    };
    this.logSocket2.onerror = (err) => console.log(err);
  }

  /**
   * 创建webSocket
   */
  createSocket3() {
    this.logSocket3 = new WebSocket(SettingUrl.URL.socket3);
    this.logSocket3.onmessage = (event) => {
      if (event.data) {
        let res = JSON.parse(event.data);
        this.logData3 += `结果:[${res.success}]，数据:${res.data || ' '}，信息:${res.info}\n`;
      }
      this.scrollBottom();
    };
    this.logSocket3.onerror = (err) => console.log(err);
  }

  /**
   * 创建webSocket
   */
  createSocket4() {
    this.logSocket4 = new WebSocket(SettingUrl.URL.socket4);
    this.logSocket4.onmessage = (event) => {
      if (event.data) {
        let res = JSON.parse(event.data);
        this.logData4 += `结果:[${res.success}]，数据:${res.data || ' '}，信息:${res.info}\n`;
      }
      this.scrollBottom();
    };
    this.logSocket4.onerror = (err) => console.log(err);
  }

  logEditor1Init(editor) {
    this.logEditor1 = editor;
  }

  logEditor2Init(editor) {
    this.logEditor2 = editor;
  }

  logEditor3Init(editor) {
    this.logEditor3 = editor;
  }

  logEditor4Init(editor) {
    this.logEditor4 = editor;
  }

  scrollBottom() {
    if (this.logEditor1) this.logEditor1.setScrollTop(this.logEditor1.getScrollHeight());
    if (this.logEditor2) this.logEditor2.setScrollTop(this.logEditor2.getScrollHeight());
    if (this.logEditor3) this.logEditor3.setScrollTop(this.logEditor3.getScrollHeight());
    if (this.logEditor4) this.logEditor4.setScrollTop(this.logEditor4.getScrollHeight());
  }

  getLog1(btnId) {
    this.homeService.getLog1(btnId);
  }

  getLog2(btnId) {
    this.homeService.getLog2(btnId);
  }

  getLog3(btnId) {
    this.homeService.getLog3(btnId);
  }

  getLog4(btnId) {
    this.homeService.getLog4(btnId);
  }

  getState() {
    this.homeService.getState().then((data: any) => {
      if (data) {
        data.forEach(item => {
          this.states[item.id] = item;
          if (item.state === 'Online') {
            this.connectSocket(item.id);
          } else {
            this.closeSocket(item.id);
          }
        });
      }
    })
  }

  closeSocket(id: string) {
    switch (id) {
      case 'client01':
        if (this.logSocket1 && this.logSocket1.readyState === 1) this.logSocket1.close();
        break;
      case 'client02':
        if (this.logSocket2 && this.logSocket2.readyState === 1) this.logSocket2.close();
        break;
      case 'client03':
        if (this.logSocket3 && this.logSocket3.readyState === 1) this.logSocket3.close();
        break;
      case 'swift03':
        if (this.logSocket4 && this.logSocket4.readyState === 1) this.logSocket4.close();
        break;
    }
  }

  connectSocket(id: string) {
    switch (id) {
      case 'client01':
        if (!this.logSocket1 || this.logSocket1.readyState === 3) this.createSocket1();
        break;
      case 'client02':
        if (!this.logSocket2 || this.logSocket2.readyState === 3) this.createSocket2();
        break;
      case 'client03':
        if (!this.logSocket3 || this.logSocket3.readyState === 3) this.createSocket3();
        break;
      case 'swift03':
        if (!this.logSocket4 || this.logSocket4.readyState === 3) this.createSocket4();
        break;
    }
  }

  ngOnDestroy(): void {
    clearInterval(this.timer);
  }
}

